// pages/my/index.ts
const myDefaultAvatarUrl = '/images/default-avatar.png'

interface UserInfo {
  avatarUrl: string;
  nickName: string;
  openId?: string;
  unionId?: string;
}

interface LoginResult {
  result: {
    success: boolean;
    data?: {
      openId: string;
      unionId?: string;
      appId?: string;
    };
    message?: string;
    error?: string;
  };
}

Page({
  data: {
    userInfo: {
      avatarUrl: myDefaultAvatarUrl,
      nickName: '',
    } as UserInfo,
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    loginLoading: false,
    showEditModal: false,
    editUserInfo: {
      avatarUrl: '',
      nickName: ''
    } as UserInfo,
    saveLoading: false,
    voteRecords: [
      {
        id: 1,
        activityId: 1,
        activityTitle: '企业年度评选',
        voteTime: '2025-05-25 14:30',
        voteCount: 3,
        candidates: [
          { id: 1, name: '张三', imageUrl: '' },
          { id: 2, name: '李四', imageUrl: '' },
          { id: 3, name: '王五', imageUrl: '' }
        ]
      },
      {
        id: 2,
        activityId: 2,
        activityTitle: '优秀员工评选',
        voteTime: '2025-04-15 10:20',
        voteCount: 2,
        candidates: [
          { id: 4, name: '赵六', imageUrl: '' },
          { id: 5, name: '钱七', imageUrl: '' }
        ]
      },
      {
        id: 3,
        activityId: 3,
        activityTitle: '最佳团队评选',
        voteTime: '2025-03-20 16:45',
        voteCount: 1,
        candidates: [
          { id: 6, name: '孙八', imageUrl: '' }
        ]
      },
      {
        id: 4,
        activityId: 4,
        activityTitle: '创新项目评选',
        voteTime: '2025-02-10 09:15',
        voteCount: 4,
        candidates: [
          { id: 7, name: '周九', imageUrl: '' },
          { id: 8, name: '吴十', imageUrl: '' },
          { id: 9, name: '郑十一', imageUrl: '' },
          { id: 10, name: '王十二', imageUrl: '' }
        ]
      },
      {
        id: 5,
        activityId: 5,
        activityTitle: '年度明星员工',
        voteTime: '2025-01-05 14:30',
        voteCount: 2,
        candidates: [
          { id: 11, name: '冯十三', imageUrl: '' },
          { id: 12, name: '陈十四', imageUrl: '' }
        ]
      },
      {
        id: 6,
        activityId: 6,
        activityTitle: '技术专家评选',
        voteTime: '2024-12-25 11:20',
        voteCount: 3,
        candidates: [
          { id: 13, name: '褚十五', imageUrl: '' },
          { id: 14, name: '卫十六', imageUrl: '' },
          { id: 15, name: '蒋十七', imageUrl: '' }
        ]
      },
      {
        id: 7,
        activityId: 7,
        activityTitle: '服务之星评选',
        voteTime: '2024-11-18 13:45',
        voteCount: 1,
        candidates: [
          { id: 16, name: '沈十八', imageUrl: '' }
        ]
      },
      {
        id: 8,
        activityId: 8,
        activityTitle: '销售冠军评选',
        voteTime: '2024-10-30 17:00',
        voteCount: 5,
        candidates: [
          { id: 17, name: '韩十九', imageUrl: '' },
          { id: 18, name: '杨二十', imageUrl: '' },
          { id: 19, name: '朱二一', imageUrl: '' },
          { id: 20, name: '秦二二', imageUrl: '' },
          { id: 21, name: '尤二三', imageUrl: '' }
        ]
      }
    ]
  },

  onLoad() {
    // 检查用户信息
    this.checkUserInfo()
    
    // 只有在用户已登录时才获取投票记录
    if (this.data.hasUserInfo) {
      this.getVoteRecords()
    }
  },

  // 检查用户信息
  checkUserInfo() {
    const userInfo = wx.getStorageSync('userInfo')
    // 只有当用户信息完整且包含openId时才认为是已登录状态
    if (userInfo && userInfo.openId && userInfo.nickName) {
      this.setData({
        userInfo,
        hasUserInfo: true
      })
      console.log('检测到已登录用户:', userInfo.nickName)
    } else {
      // 清除可能存在的不完整用户信息
      wx.removeStorageSync('userInfo')
      this.setData({
        userInfo: {
          avatarUrl: myDefaultAvatarUrl,
          nickName: '',
          openId: undefined,
          unionId: undefined
        },
        hasUserInfo: false,
        voteRecords: []
      })
      console.log('未检测到有效登录状态')
    }
  },

  // 微信一键登录
  async onLoginTap() {
    if (this.data.loginLoading) return;
    
    this.setData({ loginLoading: true });
    
    try {
      // 获取用户头像昵称（仅用于首次注册）
      const { userInfo } = await this.getUserProfile();
      
      // 调用云函数获取openId等信息并保存到数据库
      const loginResult = await wx.cloud.callFunction({
        name: 'login',
        data: {
          userInfo: {
            nickName: userInfo.nickName,
            avatarUrl: userInfo.avatarUrl
          }
        }
      });
      
      // 安全地获取云函数返回的结果
      const result = loginResult.result as any;
      
      if (result && result.success && result.data) {
        const completeUserInfo = result.data.userInfo;
        
        // 保存用户信息到本地存储
        wx.setStorageSync('userInfo', completeUserInfo);
        
        // 更新页面显示的用户信息
        this.setData({
          userInfo: completeUserInfo,
          hasUserInfo: true
        });
        
        // 登录成功后获取投票记录
        await this.getVoteRecords();
        
        wx.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 2000
        });
        
        console.log('用户登录成功:', completeUserInfo);
        console.log('用户信息已从数据库恢复');
      } else {
        throw new Error((result && result.message) || '登录失败');
      }
    } catch (error: any) {
      console.error('登录失败:', error);
      wx.showToast({
        title: error.errMsg || error.message || '登录失败，请重试',
        icon: 'error',
        duration: 2000
      });
    } finally {
      this.setData({ loginLoading: false });
    }
  },

  // 打开编辑资料弹窗
  onEditProfile() {
    this.setData({
      showEditModal: true,
      editUserInfo: {
        avatarUrl: this.data.userInfo.avatarUrl,
        nickName: this.data.userInfo.nickName,
        openId: this.data.userInfo.openId,
        unionId: this.data.userInfo.unionId
      }
    });
  },

  // 关闭编辑资料弹窗
  onCloseEditModal() {
    this.setData({
      showEditModal: false
    });
  },

  // 选择头像
  async onChooseAvatar() {
    try {
      const res = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        sizeType: ['compressed'],
        camera: 'back'
      });
      
      if (res.tempFiles && res.tempFiles.length > 0) {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        
        // 更新临时显示的头像
        this.setData({
          'editUserInfo.avatarUrl': tempFilePath
        });
      }
    } catch (error) {
      console.error('选择头像失败:', error);
      wx.showToast({
        title: '选择头像失败',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 昵称输入
  onNickNameInput(e: any) {
    this.setData({
      'editUserInfo.nickName': e.detail.value
    });
  },

  // 保存资料
  async onSaveProfile() {
    if (this.data.saveLoading) return;
    
    const { editUserInfo } = this.data;
    
    // 验证昵称
    if (!editUserInfo.nickName || editUserInfo.nickName.trim() === '') {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    this.setData({ saveLoading: true });
    
    try {
      let finalAvatarUrl = editUserInfo.avatarUrl;
      
      // 如果选择了新头像，上传到云存储
      const isTempFilePath = editUserInfo.avatarUrl.startsWith('http://tmp/') || 
                            editUserInfo.avatarUrl.startsWith('wxfile://') ||
                            editUserInfo.avatarUrl.startsWith('tmp');
      
      console.log('头像路径:', editUserInfo.avatarUrl);
      console.log('是否为临时文件:', isTempFilePath);
      
      if (isTempFilePath) {
        console.log('检测到新选择的头像，准备上传到云存储');
        const uploadResult = await this.uploadAvatar(editUserInfo.avatarUrl);
        if (uploadResult) {
          finalAvatarUrl = uploadResult;
          console.log('使用新上传的头像URL:', finalAvatarUrl);
        }
      }
      
      // 调用云函数更新用户信息
      const updateResult = await wx.cloud.callFunction({
        name: 'getUserInfo',
        data: {
          action: 'updateProfile',
          userInfo: {
            nickName: editUserInfo.nickName.trim(),
            avatarUrl: finalAvatarUrl
          }
        }
      });
      
      const result = updateResult.result as any;
      if (result && result.success) {
        // 更新本地用户信息
        const updatedUserInfo = {
          ...this.data.userInfo,
          nickName: editUserInfo.nickName.trim(),
          avatarUrl: finalAvatarUrl
        };
        
        // 保存到本地存储
        wx.setStorageSync('userInfo', updatedUserInfo);
        
        // 更新页面数据
        this.setData({
          userInfo: updatedUserInfo,
          showEditModal: false
        });
        
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        });
        
        console.log('用户资料更新成功:', updatedUserInfo);
      } else {
        throw new Error((result && result.message) || '保存失败');
      }
    } catch (error: any) {
      console.error('保存资料失败:', error);
      wx.showToast({
        title: error.message || '保存失败，请重试',
        icon: 'error',
        duration: 2000
      });
    } finally {
      this.setData({ saveLoading: false });
    }
  },

  // 上传头像到云存储
  async uploadAvatar(tempFilePath: string): Promise<string | null> {
    try {
      const { openId } = this.data.userInfo;
      if (!openId) {
        throw new Error('用户未登录');
      }
      
      console.log('开始上传头像，临时路径:', tempFilePath);
      
      // 生成文件名：用户openId
      const fileName = `${openId}.jpg`;
      const cloudPath = `./cloud-storage/users/avatars/${fileName}`;
      
      // 上传到云存储
      wx.showLoading({
        title: '上传头像中...',
        mask: true
      });
      
      const uploadResult = await wx.cloud.uploadFile({
        cloudPath: cloudPath,
        filePath: tempFilePath
      });
      
      wx.hideLoading();
      
      if (uploadResult.fileID) {
        console.log('头像上传成功:', uploadResult.fileID);
        return uploadResult.fileID;
      } else {
        throw new Error('上传失败');
      }
    } catch (error) {
      wx.hideLoading();
      console.error('上传头像失败:', error);
      wx.showToast({
        title: '头像上传失败',
        icon: 'none',
        duration: 2000
      });
      return null;
    }
  },

  // 获取用户头像昵称信息
  getUserProfile(): Promise<{ userInfo: any }> {
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途
        success: (res) => {
          resolve(res);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  // 兼容老版本的获取用户信息方法
  getUserInfo(e: any) {
    if (e.detail.userInfo) {
      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true
      })
      
      // 保存用户信息
      wx.setStorageSync('userInfo', e.detail.userInfo)
    }
  },

  // 退出登录
  onLogoutTap() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储的用户信息
          wx.removeStorageSync('userInfo');
          
          // 完全清空用户信息，恢复到未登录状态
          this.setData({
            userInfo: {
              avatarUrl: myDefaultAvatarUrl,
              nickName: '',
              openId: undefined,
              unionId: undefined
            },
            hasUserInfo: false,
            voteRecords: [] // 清空投票记录
          });
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success',
            duration: 2000
          });
        }
      }
    });
  },

  // 获取投票记录
  async getVoteRecords() {
    try {
      // 检查用户是否已登录
      if (!this.data.hasUserInfo || !this.data.userInfo.openId) {
        console.log('用户未登录，无法获取投票记录');
        this.setData({
          voteRecords: []
        });
        return;
      }
      
      // 调用新的投票管理云函数获取真实的投票记录
      const result = await wx.cloud.callFunction({
        name: 'voteManager',
        data: {
          action: 'getVoteRecords'
        }
      });
      
      const response = result.result as any;
      if (response && response.success) {
        this.setData({
          voteRecords: response.data.voteRecords || []
        });
        console.log('获取投票记录成功:', response.data.voteRecords);
      } else {
        console.error('获取投票记录失败:', response?.message);
        this.setData({
          voteRecords: []
        });
      }
    } catch (error) {
      console.error('获取投票记录失败:', error);
      this.setData({
        voteRecords: []
      });
    }
  },

  // 跳转到活动详情页
  goToActivityDetail(e: any) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/activity/detail/index?id=${id}`
    })
  },

  // 跳转到候选人详情页
  goToCandidateDetail(e: any) {
    const candidateId = e.currentTarget.dataset.candidateId
    const activityId = e.currentTarget.dataset.activityId
    
    if (!candidateId || !activityId) {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      })
      return
    }
    
    wx.navigateTo({
      url: `/pages/candidate/detail/index?id=${candidateId}&activityId=${activityId}`
    })
  },

  // 空函数，用于阻止事件冒泡
  preventTap() {
    // 只是用来阻止事件冒泡，不需要实际操作
  }
}) 